#!/usr/bin/env ruby

require 'csv'
require 'json'
require 'fileutils'
require 'optparse'

$file_name = "Localizable.strings"
$plist_file_name = "InfoPlist.strings"
$options = {}

parser = OptionParser.new do |opts|
  opts.banner =<<EOF
Usage: l10n [options] CSV_FILE"
EOF
  opts.separator ""
  opts.separator "Options:"
  opts.on("--root [root]", "proj 文件目录") do |s|
      $options[:root] = s
  end
  opts.on("--swift [SWIFT]", "swift 文件") do |s|
      $options[:swift] = s
  end
end

parser.parse!

csv_file = ARGV.shift

def exit_with_usage 
  $stderr.puts parser
  exit 1
end

def exit_with_format
  $stderr.puts "Invalid csv format"
  $stderr.puts "Format:"
  $stderr.puts "key, comment, ..."
  exit 1
end

if csv_file.nil?
  exit_with_usage
end

lines = CSV.read(csv_file, col_sep: ',')
if lines.nil?
  $stderr.puts "Unable to read #{csv_file}."
  exit 1
end

header = lines[0]

if header.count < 3
  exit_with_format
end

output = {}

num = header.count - 2

lines[1..-1].each do |line|
  key = line[0].strip
  next if key =~ /^#/
  next if key.length == 0
  comment = line[1].strip
  base = ""
  (0...num).each do |i|
    index = 2 + i
    value = line[index].strip
    base = value if i == 0
    value = value.length > 0 ? value : base
    lang = header[index].strip
    output[lang] = {} unless output[lang]
    output[lang][key] = {
      comment: comment,
      value: value
    }
  end
end

def generate_strings(trans)
  content = []
  trans.each do |key, v|
    next if key =~ /^@/
    content.push "/*#{v[:comment]}*/"
    content.push "\"#{key}\" = \"#{v[:value]}\";"
    content.push ""
  end
  content.join("\n")
end

def generate_plist_strings(trans)
  content = []
  trans.each do |key, v|
    next if key !~ /^@/
    key = key.gsub(/^@/, "")
    content.push "#{key} = \"#{v[:value]}\";"
    content.push ""
  end
  content.join("\n")
end

def generate_swift(lines)
  content = []
  content.push "/** Generated by l10n */"
  content.push ""
  content.push "public enum MyLocalizedKey: String {"
  lines[1..-1].each do |line|
    key = line[0].strip
    next if key =~ /^#/
    next if key =~ /^@/
    next if key.length == 0
    comment = line[1].strip
    case_key = key.gsub(".", "_")
    content.push "  /**#{comment}*/"
    content.push "  case #{case_key} = \"#{key}\""
  end
  content.push "}"
  content.join("\n")
end

root = $options.fetch(:root, Dir.pwd)

output.each do |lang, trans|
  dir = File.join(root, "#{lang}.lproj")
  strings_file = File.join(dir, $file_name)
  plist_file = File.join(dir, $plist_file_name)
  FileUtils.mkdir_p(dir)
  File.write(strings_file, generate_strings(trans))
  File.write(plist_file, generate_plist_strings(trans))
end

if $options[:swift]
  File.write($options[:swift], generate_swift(lines))
end
